import router from "@/router";
//进度条
import NProgress from "nprogress";
import "nprogress/nprogress.css";
//判断是否为http地址
import { isHttp } from "@/utils/validate";
import { getToken, setToken, removeToken } from "@/utils/token";
import { useUserStore } from "@/store/modules/user";
import usePermissionStore from "@/store/modules/permission";
import { isRelogin } from "@/utils/request";
NProgress.configure({ showSpinner: false });
//白名单
const whiteList = ["/login", "/register"];
router.beforeEach((to, from, next) => {
  console.log("我走路由前置 了码");

  NProgress.start(); // 开启进度条
  if (getToken()) {
    console.log("我有tokne");

    if (to.path == "/login") {
      next("/");
      NProgress.done();
    } else if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      //权限为空
      if (useUserStore().roles.length == 0) {
        isRelogin.show = true;
        useUserStore()
          .getInfo()
          .then(() => {
            console.log("我在获取权限");

            isRelogin.show = false;
            usePermissionStore()
              .generateRoutes()
              .then((accessRoutes) => {
              
                accessRoutes.forEach((route) => {
                  if (!isHttp(route.path)) {
                  
                    router.addRoute(route);
                    
                    // 动态添加可访问路由表
                  }
            
                });
                   
                if (to.fullpath == "/") {
                  var heardPath =
                    accessRoutes[0].path.split("/")[1] == ""
                      ? ""
                      : accessRoutes[0].path;
                  let pathIndex = "";
                  pathIndex =
                    heardPath + "/" + accessRoutes[0].children[0].path;
                   next({ path: pathIndex, replace: true });
                } else {
                   next({ ...to, replace: true });
                }
              });
          }).catch((e) => {
               useUserStore()
                 .logOut()
                 .then(() => {
                   ElMessage.error(err);
                   next({ path: "/login" });
                 });
            
          })
      } else {
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next("/login");
    }
  }
});
router.afterEach(() => {
  NProgress.done();
});
